# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging

from absl import app, flags

from coin.base.datetime_util import to_datetime
from coin.exchange.bitmex.kr_rest.futures_product import BitmexFuturesProduct
from coin.exchange.bitflyer_v1.kr_rest.futures_product import BitflyerFuturesProduct
from coin.exchange.okex.kr_rest.product import OkexProduct
from coin.exchange.okex_futures.kr_rest.futures_product import OkexFuturesProduct
from coin.strategy.mm.subscription import SubscriptionRequest, FeedSubscriptionRequest
from coin.strategy.mm.dumper_base import run_from_archive

from coin.feed.fastfeed.proto_feed_adapter import ProtoFeedAdapter
from coin.feed.fastfeed.feed_cache import run_from_feed_cache

FLAGS = flags.FLAGS


class Handler:
  def __init__(self):
    # self.sub_req = SubscriptionRequest('Spot', 'Okex', 'v3')
    # self.products = [OkexProduct.FromStr('BTC-USDT')]
    # self.products = [OkexFuturesProduct.FromStr('BTC-USD.QUARTER'),
    #                 OkexFuturesProduct.FromStr('BTC-USD.NEXT_WEEK')][1:]
    self.sub_req = SubscriptionRequest('Futures', 'Bitmex')
    self.products = [
        BitmexFuturesProduct.FromStr('BTC-USD.PERPETUAL'),
        BitmexFuturesProduct.FromStr('ETH-USD.PERPETUAL')
    ]
    """
    self.sub_req = SubscriptionRequest('Futures', 'Bitflyer')
    self.products = [BitflyerFuturesProduct.FromStr("BTC-JPY.PERPETUAL")]
    """

    self.from_ts = datetime.datetime(2019, 5, 15, 0, 0, 0)
    self.to_ts = datetime.datetime(2019, 5, 20, 0, 0, 0)
    self.machine = ['feed-01.ap-northeast-1.aws']

    self._last_book_ts = 0
    self._last_trade_ts = 0

  def on_book(self, book):
    if book.timestamp - self._last_book_ts > 10 * 60 * 10**9:
      print(to_datetime(book.timestamp), book.ask0().price, book.bid0().price)
      self._last_book_ts = book.timestamp

  def on_trade(self, trade):
    if trade.timestamp - self._last_trade_ts > 10 * 60 * 10**9:
      print(to_datetime(trade.timestamp), trade)
      self._last_trade_ts = trade.timestamp

  def on_liq(self, liq):
    pass

  def on_inst(self, inst):
    print(inst)

  def on_ticker(self, ticker):
    print(ticker)

  def on_book_reset(self, book_builder_name, book_builder):
    # assert self.sub_req == book_builder_name, book_builder_name
    for product in self.products:
      book_builder.subscribe_book(product, self.on_book)
      book_builder.subscribe_trade(product, self.on_trade)
      # book_builder.subscribe_instrument(product, self.on_inst)
      # book_builder.subscribe_index(product, self.on_inst)
      # book_builder.subscribe_ticker(product, self.on_ticker)
      # book_builder.subscribe_liquidation(product, self.on_liq)


def main(argv):
  handler = Handler()
  run_from_feed_cache(handler.products,
                      handler.on_book_reset,
                      handler.from_ts,
                      handler.to_ts,
                      machine=handler.machine,
                      worker_id=None)  # ['1', '2'])
  """
  handler = Handler()
  book_reset_callback = handler.on_book_reset
  # adapter = ProtoFeedAdapter(handler.on_book_reset)
  # book_reset_callback = adapter.on_book_reset

  feed_sub_req = FeedSubscriptionRequest.create(handler.products, handler.sub_req)
  run_from_archive(
      feed_sub_req,
      book_reset_callback,
      handler.from_ts,
      handler.to_ts,
      machine=handler.machine,
      worker_id='1')
  """


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')
  logging.getLogger('coin.exchange.util.feed_checker').setLevel(logging.WARNING)
  app.run(main)
